const config = require("./config");  
const express = require("express");  
const app = express();  
const mysql = require("mysql");  
const api = require("./routes/users");  
const banner = require("./routes/banner");  
const bodyParser = require('body-parser');  
  
app.use(bodyParser.json());  
app.use(bodyParser.urlencoded({ extended: true }));  
  
const env = {  
    host: "localhost",  
    user: "root",  
    password: "root",  
    database: "dashuaibi",  
    connectionTimeout: 30000  
};  
  
function handleError(err) {  
    if (err) {  
        // 如果断开连接，自动重连  
        if (err.code === 'PROTOCOL_CONNECTION_LOST') {  
            connect();  
        } else {  
            console.error(err.stack || err);  
        }  
    }  
}  
  
let connection; // 声明 connection 变量  
  
function connect() {  
    connection = mysql.createConnection(env);  
    connection.connect((err) => {  
        if (err) throw err;  
        // 调用 api 函数，将 app 和 connection 作为参数传递  
        api(app, connection);  
        banner(app, connection);  
    });  
    connection.on('error', handleError); // 监听错误事件  
}  
  
connect(); // 连接数据库  
app.listen(config.app.port, () => {  
    console.log(`项目启动成功，端口号：${config.app.port}`);  
});